package org.tools;

import javafx.application.Platform;
import org.App;
import org.callTools.CallBackApi;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.pojo.MenuData;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

public class SdData {
    public static Map<String, String> map = new HashMap<String, String>();
    static {
        map.put("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36");
        map.put("content-type","application/x-www-form-urlencoded");
        map.put("accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
    }
    public static void initUrl(int page, String className, CallBackApi callBackApi){
        try {

            Document doc = Jsoup.connect("https://aitool.ai/stablediffusion/models/page/"+page).headers(map).get();
            Elements links = doc.getElementsByClass("card-book list-item");

            Elements title =doc.getElementsByClass("list-subtitle text-muted text-xs overflowClip_1");


            Elements paGesSize = doc.getElementsByClass("page-numbers");
            int pageSize = Integer.parseInt(paGesSize.get(paGesSize.size()-1).html().replaceAll(",",""));
            Elements tourl = doc.getElementsByClass("media-content");

            for(int i = 0; i < links.size(); i++){
                MenuData menuData = new MenuData();
                menuData.setMaxPage(pageSize);
                menuData.setToUrl(tourl.get(i).attr("href"));
                menuData.setClassName(className);
                menuData.setPages(page);
                menuData.setNameUrl(title.get(i).html());
                menuData.setImgUrl(textCenter(tourl.get(i).attr("data-bg"),"url(",")"));
                menuData.setDownLoad(menuData.getToUrl());
                callBackApi.data(menuData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static String loadFiles(String u){
        Document downLoad = null;
        try {
            downLoad = Jsoup.connect(u).headers(map).get();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String urs = downLoad.getElementsByClass("btn btn-danger custom_btn-d py-0 px-1 mx-auto down_count text-sm").attr("href");
        String cat =get_civitai_down_url("https://aitool.ai/wp-admin/admin-ajax.php?action=get_civitai_down_url&url="+urs);
//        System.out.println("https://aitool.ai/wp-admin/admin-ajax.php?action=get_civitai_down_url&url="+urs);
        System.out.println("下载解析中...... 下载过程中已经提交后台使用");
        return cat;
    }
    public static String get_civitai_down_url(String download){
        try {
            // 创建URL对象
            URL url = new URL(download);

            // 创建HttpURLConnection对象并设置请求方法为GET
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36");
            conn.setRequestProperty("Accept-Language","en-US,en;q=0.8,zh-Hans-CN;q=0.5,zh-Hans;q=0.2");
            conn.setRequestProperty("Host"," civitai-delivery-worker-prod-2023-05-19.5ac0637cfd0766c97916cefa3764fbdf.r2.cloudflarestorage.com");
            conn.setRequestProperty("content-type","application/x-www-form-urlencoded");
            conn.setRequestProperty("accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/xaml+xml, application/x-ms-xbap, */*");
            conn.setRequestProperty("Connection","close");


            conn.setConnectTimeout(5000); // 设置连接超时时间为5秒
            conn.setReadTimeout(10000); // 设置读取超时时间为10秒
            // 获取响应状态码
            int responseCode = conn.getResponseCode();
//            System.out.println("Response Code: " + responseCode);

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            conn.disconnect();
            return response.toString();
//            System.out.println("Response Body: " + response.toString());
        } catch (IOException e) {
            System.err.println("Error sending HTTP request: " + e.getMessage());
        }
        return null;
    }
    public static int  downLoad_Win(String url,String pathFileName){
        String urls = SdData.loadFiles(url);
        return downLoadPowerShell_Win(urls,pathFileName+textCenter(urls,"%3D%22","%22&X-Amz-Algorithm"));
    }
    /**
     * powershell 下载命令  New-Object System.Net.WebClient
     * @param url 下载地址
     * @param pathFileName   存放的下载路径包含后缀名
     * @return -1代表失败 0代表成功
     */
    public static int  downLoadPowerShell_Win(String url,String pathFileName){
        int exitCode = -1;
        try {
            // 创建进程生成器
            Process process = Runtime.getRuntime().exec("powershell -ExecutionPolicy Bypass -Command \"(New-Object System.Net.WebClient).DownloadFile('"+url+"', '"+pathFileName+"')\"");
            exitCode = process.waitFor();
            if (exitCode == 0) {
                System.out.println("文件下载成功");
                App.downLen--;
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        App.stage.setTitle("www.snailcatmall.com - SD模型批量下载工具"+" 下载队列： "+App.downLen);
                    }
                });

            } else {
                System.err.println("文件下载失败，错误代码：" + exitCode+"   请先确认是否开启代理！否则无法下载");
                App.downLen--;
                Platform.runLater(new Runnable() {
                    @Override
                    public void run() {
                        App.stage.setTitle("www.snailcatmall.com - SD模型批量下载工具"+" 下载队列： "+App.downLen);
                    }
                });
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return exitCode;
    }
    /**
     * 取中间文本
     * @param allText  主要内容
     * @param index_x  左边
     * @param index_z  右边
     * @return  返回内容
     */
    public static String textCenter(String allText, String index_x, String index_z) {
        if (allText==null || allText.length() > 0){
            int index_head = allText.indexOf(index_x, 0);
            if (index_head >= 0) {
                index_head += index_x.length();
            }
            int index_end = allText.indexOf(index_z, index_head);
            if (index_head < 0 || index_end < 0) {
                return "";
            }
            String Addr = allText.substring(index_head, index_end);
            return Addr;
        }else {
            return UUID.randomUUID().toString();
        }
    }
    /**
     * 根据URL地址获取文件
     * @param path URL网络地址
     * @return File
     */
    private static File getFileByHttpURL(String path){
        String newUrl = path.split("[?]")[0];
        String[] suffix = newUrl.split("/");
        //得到最后一个分隔符后的名字
        String fileName = suffix[suffix.length - 1];
        File file = null;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try{
            file = File.createTempFile("report",fileName);//创建临时文件
            URL urlFile = new URL(newUrl);
            inputStream = urlFile.openStream();
            outputStream = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead=inputStream.read(buffer,0,8192))!=-1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (null != outputStream) {
                    outputStream.close();
                }
                if (null != inputStream) {
                    inputStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

}
